//
//  HMSportTrack.m
//  HMSport
//
//  Created by apple on 2017/4/21.
//  Copyright © 2017年 itheima. All rights reserved.
//

#import "HMSportTrack.h"
#import "HMSportSpeaker.h"

@implementation HMSportTrack{
    //记录的每一段折线的起点
    CLLocation *_source;
    //折线集合
    NSMutableArray <HMSportPolyline *> *_polylines;
    //记录上一次的GPS位置信息
    CLLocation *_preGPSLoaction;
    //语音播报器
    HMSportSpeaker *_speaker;
}

@synthesize totalTime = _totalTime;
@synthesize totalDistance = _totalDistance;
@synthesize avgSpeed = _avgSpeed;
@synthesize maxSpeed = _maxSpeed;


- (instancetype)initWithSportType:(HMSportType)sportType withSportState:(HMSportState)state{
    
    self = [super init];
    if (self) {
        
        //记录运动类型
        _sportType = sportType;
        //设置运动类型图片
        //判断运动类型
        NSString *sportTypeImgName;
        switch (_sportType) {
            case HMSportTypeRunning:
                sportTypeImgName = @"map_annotation_run";
                break;
            case HMSportTypeRiding:
                sportTypeImgName = @"map_annotation_bike";
                break;
            case HMSportTypeWalking:
                sportTypeImgName = @"map_annotation_walk";
                break;
            default:
                break;
        }
        _sportTypeImgName = sportTypeImgName;
        //记录运动状态
        _sportState = state;
        _polylines = [NSMutableArray array];
        
        
        //创建播报器
        _speaker = [[HMSportSpeaker alloc] init];
        //播报开始运动
        [_speaker startSportWithSportType:_sportType];
    }
    return self;
}


- (HMSportPolyline *)appendPolylineWithDest:(CLLocation *)dest{
    //整距离播报
    [_speaker reportSportWithDistance:_totalDistance andTime:_totalTime andAvgSpeed:_avgSpeed];
    
    //计算GPS强度, 如果GPS差/断开,则不再生成折线
    if ([self calculateGPSStateWithLocation:dest] < HMSportGPSStateNormal) {
        
        return nil;
    }
    
    //判断运动状态
    if (self.sportState != HMSportStateContinue) {
        //暂停/结束运动时,停止生成折线
        //清空记录的折线起点
        _source = nil;
        return nil;
    }
    
    //判断首次调用
    if (_source == nil) {
        
        //记录起点
        _source = dest;
        //生成起点大头针模型
        _startAnno = [[MAPointAnnotation alloc] init];
        _startAnno.coordinate = dest.coordinate;
        
        return nil;
    }
    
    //创建折线
    HMSportPolyline *polyline = [HMSportPolyline polylineWithSourceLocation:_source andDestLocation:dest];
    //将折线模型进行记录
    [_polylines addObject:polyline];
    
    //记录下一段的起点
    _source = dest;
    
    return polyline;
}

//计算GPS强度
- (HMSportGPSState)calculateGPSStateWithLocation:(CLLocation *)location{

    HMSportGPSState state = HMSportGPSStateBad;
    
    //判断是否在室内
    if (location.speed < 0) {
        
        //发送gps更新通知
        [[NSNotificationCenter defaultCenter] postNotificationName:@"HMSportGPSStateDidChangeNote" object:nil userInfo:@{@"HMSportGPSStateDidChangeNoteGPSStateKey": @(state)}];
        
        return state;
    }
    
    if (_preGPSLoaction == nil) {
        
        _preGPSLoaction = location;
        
        
        return state;
    }
    
    //GPS精确度时间差
    double deltaTime = ABS([location.timestamp timeIntervalSinceDate:_preGPSLoaction.timestamp] - 1);
    
    // 06:55:31  06:55:30  06:55:33  06:55:34
    
    if (deltaTime > 1) { //GPS差
        
        
    } else if (deltaTime <= 1 && deltaTime >= 0.01) { //一般
    
        state = HMSportGPSStateNormal;
        
    } else { //GPS好
    
        state = HMSportGPSStateGood;
    }
    
    _preGPSLoaction = location;
    
    //发送gps更新通知
    [[NSNotificationCenter defaultCenter] postNotificationName:@"HMSportGPSStateDidChangeNote" object:nil userInfo:@{@"HMSportGPSStateDidChangeNoteGPSStateKey": @(state)}];
    
    return state;
}


#pragma mark - setter & getter


- (void)setSportState:(HMSportState)sportState{

    _sportState = sportState;
    //播报运动状态
    [_speaker changeSportState:_sportState];
}

- (CGFloat)totalTime{
    //求集合中元素的某个属性的和 可以使用kvc来进行运算
    _totalTime = [[_polylines valueForKeyPath:@"@sum.time"] floatValue];
    return _totalTime;
}

- (CGFloat)maxSpeed{
    //求集合中元素的某个属性的和 可以使用kvc来进行运算
    _maxSpeed = [[_polylines valueForKeyPath:@"@max.speed"] floatValue];
    return _maxSpeed;
}


- (CGFloat)avgSpeed{
    //求集合中元素的某个属性的和 可以使用kvc来进行运算
    _avgSpeed = [[_polylines valueForKeyPath:@"@avg.speed"] floatValue];
    return _avgSpeed;
}

- (CGFloat)totalDistance{
    //求集合中元素的某个属性的和 可以使用kvc来进行运算
    _totalDistance = [[_polylines valueForKeyPath:@"@sum.distance"] floatValue];
    return _totalDistance;
}

- (NSString *)timeStr{

    int time = (int) _totalTime;
    return [NSString stringWithFormat:@"%02d:%02d:%02d", time / 3600, (time % 3600) / 60, time % 60];
}

@end
